package com.ft.turorial.spring.boot.security.oauth2.realm;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse;
import org.apache.oltu.oauth2.client.response.OAuthResourceResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ft.turorial.spring.boot.security.oauth2.authc.OAuth2Token;
import com.ft.turorial.spring.boot.security.oauth2.exception.OAuth2AuthenticationException;

public class OAuth2Realm extends AuthorizingRealm {
	Logger log = LoggerFactory.getLogger(getClass());
	
    private String clientId;
    private String clientSecret;
    private String accessTokenUrl;
    private String userInfoUrl;
    private String redirectUrl;
    //授权 role permission
  	private String authorizationUrl;
  	
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;//表示此Realm只支持OAuth2Token类型
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    	String userName = (String)principals.getPrimaryPrincipal();
    	//实现code客户端缓存(ehcache\redis等)后，就可以获取角色信息了
		String accessToken = "";
        if(!accessToken.equals("")){
        	authorizationInfo.addRoles(parseRole(accessToken));
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        OAuth2Token oAuth2Token = (OAuth2Token) token;
        String code = oAuth2Token.getAuthCode();
        //获取accessToken,并需要在此将accessToken缓存在本地客服务或集群服务器上，以备下一次获取用户基本信息或角色时，直接从缓存获取。【在分布式中补充】
        String accessToken = getAccessToken(code);
        String userName = null;
        if(null!=accessToken){
        	userName = extractUsername(accessToken);
        }
        
        SimpleAuthenticationInfo authenticationInfo =
                new SimpleAuthenticationInfo(userName, code, getName());
        return authenticationInfo;
    }
    
    /**
     * 获取用户角色权限信息
     * @param code
     * @return
     */
    private List<String> parseRole(String accessToken) {
		String rlt="";
		try {
			OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
			// 获取user info
			OAuthClientRequest userInfoRequest = new OAuthBearerClientRequest(authorizationUrl).setAccessToken(accessToken)
					.buildQueryMessage();
			OAuthResourceResponse resourceResponse = oAuthClient.resource(userInfoRequest, OAuth.HttpMethod.GET,
					OAuthResourceResponse.class);
			rlt = resourceResponse.getBody();
		} catch (Exception e) {
			throw new AuthenticationException(e);
		}
		
		log.debug("OAuth2 server response,{}",rlt);
		List<String> list = new ArrayList<String>();
		if (StringUtils.isEmpty(rlt)) {
			return list;
		}
		
		try{
			JSONArray roleArray =	JSON.parseArray(rlt);
			for(Object json:roleArray){
				list.add(json.toString());
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		return list;
	}
    
    /**
     * 获取用户名(可以扩展oauth2server 返回更多基本信息)
     * @param code
     * @return
     */
    private String extractUsername(String accessToken) {

        try {
            OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
            // 获取user info
            OAuthClientRequest userInfoRequest = new OAuthBearerClientRequest(userInfoUrl)
                    .setAccessToken(accessToken).buildQueryMessage();
            OAuthResourceResponse resourceResponse = oAuthClient.resource(userInfoRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
            String userName = resourceResponse.getBody();
            return userName;
        } catch (Exception e) {
            e.printStackTrace();
            throw new OAuth2AuthenticationException(e);
        }
    }
    
    private String getAccessToken(String code) {
        try {
        	OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

            OAuthClientRequest accessTokenRequest = OAuthClientRequest
                    .tokenLocation(accessTokenUrl)
                    .setGrantType(GrantType.AUTHORIZATION_CODE)
                    .setClientId(clientId)
                    .setClientSecret(clientSecret)
                    .setCode(code)
                    .setRedirectURI(redirectUrl)
                    .buildQueryMessage();
            // 获取access token
            OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(accessTokenRequest, OAuth.HttpMethod.POST);
            //Long expiresIn = oAuthResponse.getExpiresIn();
            String accessToken = oAuthResponse.getAccessToken();
            
            return accessToken;
		} catch (OAuthSystemException e) {
			e.printStackTrace();
		} catch (OAuthProblemException e) {
			e.printStackTrace();
		}
        return null;
    }
    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public void setClientSecret(String clientSecret) {
        this.clientSecret = clientSecret;
    }

    public void setAccessTokenUrl(String accessTokenUrl) {
        this.accessTokenUrl = accessTokenUrl;
    }

    public void setUserInfoUrl(String userInfoUrl) {
        this.userInfoUrl = userInfoUrl;
    }

    public void setRedirectUrl(String redirectUrl) {
        this.redirectUrl = redirectUrl;
    }

	public String getAuthorizationUrl() {
		return authorizationUrl;
	}

	public void setAuthorizationUrl(String authorizationUrl) {
		this.authorizationUrl = authorizationUrl;
	}
}
